﻿using System.Web.UI;
using Microsoft.SharePoint;
using System;
using TNO.Education.Helpers;

namespace TNO.Education
{
    public class BaseControl : UserControl
    {
        protected const int CacheMinutes = 3;

        #region Properties

        protected string BaseUrl
        {
            get
            {
                int endIndex = SPContext.Current.Web.Url.IndexOf("?");
                if (endIndex != -1)
                    return SPContext.Current.ListItemServerRelativeUrl.Substring(0, endIndex + 1);
                else
                    return SPContext.Current.ListItemServerRelativeUrl;
            }
        } 
        #endregion

        #region Events
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if (!base.IsPostBack)
            {
                // Block cookie less visit attempts
                if (IsFirstVisit())
                {
                    if (!ActionValidator.IsValid(ActionValidator.ActionTypeEnum.FirstVisit)) Response.End();
                }
                else
                {
                    if (!ActionValidator.IsValid(ActionValidator.ActionTypeEnum.Revisit)) Response.End();
                }
            }
            else
            {
                // Limit number of postbacks
                if (!ActionValidator.IsValid(ActionValidator.ActionTypeEnum.Postback)) Response.End();
            }
        } 
        #endregion

        #region Methods
        private bool IsFirstVisit()
        {
            if (Session["IsFirstVisit"] == null)
            {
                Session["IsFirstVisit"] = false;
                return true;
            }
            else
            {
                return false;
            }
        } 
        #endregion

    }
}
